package io.task.cc.network.maintain;

import io.task.cc.network.ChannelContext;
import io.task.cc.network.Node;
import io.task.cc.network.utils.lock.LockedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.Lock;

/**
 * 一对一  (ip:port <--> ChannelContext)<br>
 */
public class ClientNodes {
    private static final Logger log = LoggerFactory.getLogger(ClientNodes.class);

    /**
     * remoteAndChannelContext key: Node value: ChannelContext.
     */
    private final LockedMap<Node, ChannelContext> map = new LockedMap<>();


    public static Node getKey(ChannelContext channelContext) {
        Node clientNode = channelContext.getClientNode();
        return Objects.requireNonNull(clientNode, "client node is null");
    }


    public ChannelContext find(Node clientNode) {
        Lock lock = map.readLock();
        lock.lock();
        try {
            Map<Node, ChannelContext> m = map.getT();
            return m.get(clientNode);
        } finally {
            lock.unlock();
        }
    }


    public ChannelContext find(String ip, int port) {
        return find(new Node(ip, port));
    }

    /**
     * 添加映射
     */
    public void put(ChannelContext channelContext) {

        try {
            Node clientNode = getKey(channelContext);
            map.put(clientNode, channelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * Removes映射
     */
    public void remove(ChannelContext channelContext) {

        try {
            Node clientNode = getKey(channelContext);
            map.remove(clientNode);
        } catch (Throwable e) {
            log.error(e.toString(), e);
        }
    }
}
